package masking.wechat.sdk.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * @author Jarvis.Jin
 *
 */
public class EncryptUtils {

	/**
	 * md5 加密
	 * 
	 * @param input
	 *            明文
	 * @return
	 */
	public static String md5(String input) {
		String result;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] thedigest = md.digest(input.getBytes());

			int i;

			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < thedigest.length; offset++) {
				i = thedigest[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}

			result = buf.toString();
		} catch (NoSuchAlgorithmException e) {
			result = null;
		}
		return result;
	}

	/**
	 * sha1 加密
	 * 
	 * @param input原文
	 * @return
	 */
	public static String sha1(String input) {
		try {
			MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
			digest.update(input.getBytes());
			byte messageDigest[] = digest.digest();
			// Create Hex String
			StringBuffer hexString = new StringBuffer();
			// 字节数组转换为 十六进制 数
			for (int i = 0; i < messageDigest.length; i++) {
				String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexString.append(0);
				}
				hexString.append(shaHex);
			}
			return hexString.toString();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}

	// public static void main(String args[]) throws Exception{
	// /** 本工具类AES加密使用示例 */
	// String miWen = aesEncrypt("123456", "PE0ItO1d0sNsTAXYoCX9NQ==");
	// System.out.println(miWen);
	// System.out.println(aesDecrypt(miWen,"PE0ItO1d0sNsTAXYoCX9NQ=="));
	//
	// /** 本工具类SHA1加密使用示例 */
	// System.out.println(sha1("121323"));
	//
	// }

	/**
	 * 
	 * @param originText
	 *            需要被加密的字符串
	 * @param secret
	 *            加密需要的secret
	 * @return 密文
	 * @throws Exception
	 */
	public static String aesEncrypt(String originText, String secret) throws Exception {
		AesCypher cypher = new AesCypher(secret);
		return cypher.encrypt(originText);
	}

	/**
	 * 
	 * @param encryptedText
	 *            需要被解密的字符串
	 * @param secret
	 *            加密需要的secret
	 * @return 明文
	 * @throws Exception
	 */
	public static String aesDecrypt(String encryptedText, String secret) throws Exception {
		AesCypher cypher = new AesCypher(secret);
		return cypher.decrypt(encryptedText);
	}

	public static String getRandomString(int length) { // length表示生成字符串的长度
		String base = "abcdefghijklmnopqrstuvwxyz0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

}